<?php
namespace Admin\Controller;
use Lib\Controller\AdminBaseController;

class RoleController extends AdminBaseController{
    private $provinceModel;
    private $cityModel;
    private $Admin;
    private $Role;
    private $Access;
    private $Menu;
    private $agentModel;
    
    public function __construct(){
        $this->provinceModel = D('Province');       //省份
        $this->cityModel     = D('City');           //城市
        $this->Admin         = D("ServerAdmin");
        $this->Role          = D("Role");
        $this->Access        = D("Access");
        $this->Menu          = D("Menu");
        $this->agentModel    = D('Agent');
        parent::__construct();
    }
    /**
     * 后台管理员列表
     */
    public function admin_list(){
        $where['id'] = session('adminId');
        $adminInfo = $this->Admin->find_admin($where); 
//         p($adminInfo);p($this->Admin->getLastSql());return;
        if($adminInfo['role_id']==1){
            $allAdmin = $this->Admin->find_admin();
            $accessList = $this->Role->getAccess($allAdmin);
        }else{
            unset($where);
            $where['store_id'] = $adminInfo['store_id'];
            $allAdmin = $this->Admin->select_admin($where);
            $accessList = $this->Role->getAccess($allAdmin);
        }
        foreach ($accessList as $key => $value){
            $accessList[$key]['create_time'] = date("Y-m-d H:i:s", $value['create_time']);
            $accessList[$key]['update_time'] = date("Y-m-d H:i:s", $value['update_time']);
        }
//         p($accessList);
        $this->assign('accessList',$accessList);
        $this->display();
    }
    
//     /**
//      * 编辑管理员
//      */
//     public function edit_admin(){
//         if(IS_GET){
//             $where['id'] = I('get.id');
//             $adminInfo = $this->Admin->find_admin($where);
// //             p($adminInfo);
//             $this->assign('adminInfo',$adminInfo);
//             $this->assign('type',I('get.type'));
//             $this->display();
//         }
//         if(IS_POST){
//             $where['id'] = I('post.adminInfoId');
//             $adminInfo = $this->Admin->find_admin($where);
//             $data['user_name'] = I('post.user_name');
//             if(I('post.password')==''){
//                 $data['user_password'] = $adminInfo['user_password'];
//             }else{
//                 $data['user_password'] = md5(I('post.password').$adminInfo['user_salt']);
//             }
//             $data['avatar_img'] = I('post.avatar_img', '');
//             $data['nick_name'] = I('post.nick_name');
//             $data['about'] = I('post.about');
//             $update = $this->Admin->update_admin($where,$data);
            
//             if($update !==false){
//                 $this->tyAjaxReturn(1, L('保存成功'), U(MODULE_NAME.'/Role/admin_list'));
//             }else{
//                 $this->tyAjaxReturn(0, L('保存失败'));
//             }
//         }
//     }
    
    /**
     * 添加管理员
     */
    public function add_admin() {
        if (IS_POST) {
            //验证密码
            $data['role_id']        = I('post.rold_id');
            $data['admin_name']     = I('post.user_name');
            $data['admin_password'] = md5(I('post.password'));
            $data['remark']         = I('post.about');
            $data['create_time']    = time();
            $data['update_time']    = time();
            
            //密码格式
            if ($data['admin_password'] != md5(I('post.repassword'))) {//判断密码一致   
                $this->tyAjaxReturn(0, '两次输入的密码不一致');
            }
            if($data['role_id'] == '5'){
                $agentData['agent_name'] = I('post.user_name');
                $agentData['agent_password'] = md5(I('post.password'));
                $agentData['create_time'] = time();
                $agentData['proportion'] = I('post.proportion')/100;
                $agentData['city_id'] = substr(I('post.city_id'),0,strlen(I('post.city_id'))-1);
                
                $agentResult = $this->agentModel->add($agentData);
            }
            $result = $this->Admin->add($data);
            if($result){
                $this->tyAjaxReturn(1, '添加成功' , U(MODULE_NAME.'/Role/admin_list') );
            }else{
                $this->tyAjaxReturn(1, '添加失败，请稍后再试' );
            }
        } else {
            //获取角色列表
            $roleList = $this->_getRoleList();
            //获取省
            $province = $this->provinceModel->select();
            $city     = $this->cityModel->select();
            
            $this->assign('city',$city);
            $this->assign('roleList', $roleList);
            $this->assign('province',$province);
            $this->display('edit_admin');
        }
    }
    
    /**
     * 获取角色列表
     * @return type
     */
    private function _getRoleList() {
        $roleList = $this->Role->where('id = '.session('roleId'))->find();
        if (!$roleList || $roleList['id'] != '1') {
            //重定向到添加角色操作
            redirect(U(MODULE_NAME.'/Orders/orders_list'), 3, '抱歉！你没有权限添加管理员');
        }
        return $this->Role->select();
    }
    
    
    public function changeFrontRoleList() {
        if(IS_AJAX){
            $roleList = $this->Role->where(array('id' => array('gt', 1), 'status' => array('gt', 0), 'type' => array('eq',1) ))->select();
            $this->tyAjaxReturn(1,'',null,$roleList,null);
        }
    }
    
    
    public function changeBehindRoleList() {
        if(IS_AJAX){
            $roleList = $this->Role->where(array('id' => array('gt', session('roleId')), 'status' => array('gt', 0), 'type' => array('eq',2) ))->select();
            $this->tyAjaxReturn(1,'',null,$roleList,null);
        }
    }
    

    
    /**
     * 删除管理员
     */
    public function delete_admin(){
        $where['id'] = I('get.id');
        $result = $this->Admin-> deleteAdmin($where);
        if($result){
            $this->tyAjaxReturn(1,'删除成功',U(MODULE_NAME . '/Role/admin_list'));
        }else{
            $this->tyAjaxReturn(0,'删除失败');
        }
    }
    
    /**
     * 角色列表
     */
    public function role_list(){
        $roleList = $this->Role->select();
        $this->assign('roleList',$roleList);
        $this->display();
    }
    
    /**
     * 编辑角色
     */
    public function edit_role(){
        if(IS_GET){
            $where['id'] = I("get.id",'');
            $result = $this->Role->findRole($where);
            $this->assign('roleInfo',$result);
            $this->display();
        }
        if(IS_POST){
            $data['name'] = I('post.name','');
            $data['remark'] = I('post.remark','');
            $data['status'] = I('post.status',1);
            if(I('post.type') == 'add'){
                $result = $this->Role->add($data);
                if($result){
                    $this->tyAjaxReturn(1,'添加成功',U(MODULE_NAME . '/Role/role_list'));
                }else{
                    $this->tyAjaxReturn(0,'添加失败');
                }
            }else{
                $where['id'] = I('post.id','');
                $result = $this->Role->updateRole($where,$data);
                if($result){
                    $this->tyAjaxReturn(1,'修改成功',U(MODULE_NAME . '/Role/role_list'));
                }else{
                    $this->tyAjaxReturn(0,'修改失败');
                }
            }
            
        }
    }
    
    /**
     * 修改角色状态
     */
    public function change_role_status(){
        $id = I('get.id', '', 'int');
        if ($id == '' || $id == C('SUPER_ADMIN_ROLE_ID')) {
            $this->tyAjaxReturn(0, '超级管理员不可修改');
        }
        $where['id'] = $id;
        $data = $this->Admin->find_admin($where);
        //查询之前状态
        //$data = $this->Role->field('status')->find($id);
    
        $status = $data['status'] > 0 ? 0 : 1;
    
        $result = $this->Admin->where(array('id' => $id))->save(array('status' => $status,'update_time' => time()));
    
        if ($result > 0) {
            $this->tyAjaxReturn(1, '修改成功！');
        } else {
            $this->tyAjaxReturn(0, '修改失败！');
        }
    }
    
    
    public function B2C_change_role_status(){
        $id = I('get.id', '', 'int');
        $where['id'] = $id;
        $data = $this->shopUser->where($where)->find();
        
        //$this->ajaxReturn($data);
        
        $status = $data['admin_status'] > 0 ? 0: 1;
        $result = $this->shopUser->where($where)->save(array('admin_status' => $status,'update_time' => time()));
        
        if ($result > 0) {
            $this->tyAjaxReturn(1, '修改成功！');
        } else {
            $this->tyAjaxReturn(0, '修改失败！');
        }
    }
    
    /**
     * 设置权限
     */
    public function edit_access(){
        if(IS_GET){
            $roleId['id'] = I('get.id', '', 'int');
            if ($roleId == C('SUPER_ADMIN_ROLE_ID') || empty($roleId)) {
                $this->error('超级管理员不能设置');
            }
            //获取角色信息
            $roleInfo = $this->Role->findRole($roleId);
            //菜单列表
            $menuList = M('Menu')->select();
            //原有权限
            $originalAccess = $this->Access->where(array('role_id' => $roleId['id'],'access_type' => '2'))->select();
            $originalMenuList = array();
            //提取菜单id
                foreach ($originalAccess as$w=> $val) {
                    $originalMenuList [$w] = $val['access_type_id'];
                }
            $accessInfo = arrayMerge($menuList, $originalMenuList);
            $this->assign('originalMenuList',$originalMenuList);
            $this->assign('originalAccess',$originalAccess);
            $this->assign('roleInfo', $roleInfo);
            $this->assign('access', $accessInfo);
            $this->display();
        }
        if(IS_POST){
            $roleId = I('post.role_id', '', 'int');
            if (empty($roleId) || $roleId == C('SUPER_ADMIN_ROLE_ID')) {
                $this->tyAjaxReturn(0, '超级管理员不能设置');
            }
            $accessList = I('post.access');
            foreach($accessList as$w=> $access){
                $aa = $this->Menu->field('p_id')->where(array('id'=>$access))->find();
                foreach($aa as$q=> $bb){
                    $pId[$w] = $bb;
                }
            }
            $pId = array_unique($pId);//array_unique函数去除数组内重复的元素
            foreach($pId as$x=>$p_id){
                $cc = $this->Menu->field('p_id')->where(array('id'=>$p_id))->find();
                foreach($cc as$e=> $dd){
                    $cp_Id[$x] = $dd;
                }
            }
            $cp_Id = array_unique($cp_Id);
            $array = array_merge($pId,$cp_Id);
            $accessList = array_merge($accessList,$array);
            //删除原有权限
            $this->Access->where(array('role_id' => $roleId,'access_type' => '2'))->delete();
            
            //添加新权限
            foreach ($accessList as $val) {
                $data['role_id'] = $roleId;
                $data['access_type'] = 2;
                $data['access_type_id'] = $val;
                $data['access_status'] = 1;
                $this->Access->add($data);
            }
            $this->tyAjaxReturn(1, '权限设置成功！', U(MODULE_NAME.'/Role/role_list'));
        }
        
    }
    
    
    /**
     * 此方法仅用JS表单验证测试
     * 测试邮箱是否存在
     */
    public function check_email() {
        $email = I('email', '');
        $count = $this->bbsAdmin->where(array('user_name' => $email))->count();
        if ($count > 0) {
            $this->tyAjaxReturn(0, "邮箱已存在");
        } else {
            $this->tyAjaxReturn(1, "");
        }
    }
    

    /**
     * 设置页面元素权限
     */
    public function edit_power(){
        if(IS_GET){
            $roleId['id'] = I('get.id', '', 'int');
            if ($roleId == C('SUPER_ADMIN_ROLE_ID') || empty($roleId)) {
                $this->error('超级管理员不能设置');
            }
            //获取角色信息
            $roleInfo = $this->Role->findRole($roleId);
            //页面元素列表
            $pageList = M('Page')->select();
            //原有权限
            $originalAccess = $this->Access->where(array('role_id' => $roleId['id'],'access_type' => '1'))->select();
            foreach($originalAccess as$x=>$val){
                $originalMenuList [$x] = $val['access_type_id'];
            }
            foreach($pageList as$y=> $page){
                if($page['id']==$originalMenuList[$y]){
                    $pageList[$y]['is_checked'] = 1;
                }else{
                    $pageList[$y]['is_checked'] = 0;
                }
            }
            $this->assign('roleInfo',$roleInfo);
            $this->assign('pageList',$pageList);
            $this->assign('originalAccess',$originalAccess);
            $this->display();
        }
        if(IS_POST){
            $roleId = I('post.role_id', '', 'int');
            if (empty($roleId) || $roleId == C('SUPER_ADMIN_ROLE_ID')) {
                $this->tyAjaxReturn(0, '超级管理员不能设置');
            }
            $accessList = I('post.access');
            //删除原有权限
            $this->Access->where(array('role_id' => $roleId,'access_type' => '1'))->delete();
            //添加新权限
            foreach ($accessList as $val) {
                $data['role_id'] = $roleId;
                $data['access_type'] = 1;
                $data['access_type_id'] = $val;
                $data['access_status'] = 1;
                $this->Access->add($data);
            }
            $this->tyAjaxReturn(1, '权限设置成功！', U(MODULE_NAME.'/Role/role_list'));
        }
    }
    
    
}
?>